package com.example.reagent_management.service

import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import com.example.lib_base.utils.PrecisionUtils
import com.example.lib_base.utils.RandomNumberForRate
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class StateService : LifecycleService() {
    //    val share : ShareViewModel = ShareViewModel()
    //一个Service维护自己的数值
      val states: MutableLiveData<StateRefrigerator>
                  = MutableLiveData()

    override fun onCreate() {
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e("TAG", "onBind: "+"服务销毁了", )
    }

    inner class StateBinder : Binder() {
        val service: StateService = this@StateService
        fun getSateService() : StateService{
            return service
        }
    }

    //binder通信 其实直接LiveData好像也行
    override fun onBind(intent: Intent): IBinder {
        super.onBind(intent)
        Log.e("TAG", "onBind: "+"服务绑定了", )
        lifecycleScope.launch {
            val separates = listOf<Double>(25.0,28.0) //温度正常
            val rate = listOf(0.01f,0.98f,0.01f)  //概率分段 0.01 0.98 0.01
            val separatesHu = listOf<Double>(35.0,40.0)  //湿度正常
            while (true) {
                delay(1000)
                val state = StateRefrigerator(0.0,0.0)
                state.temp = PrecisionUtils.round(
                    RandomNumberForRate.produceRateRandomNumber(-20.0, 30.0,separates,rate),
                    2)
                state.humidity = PrecisionUtils.round(
                    RandomNumberForRate.produceRateRandomNumber(30.0, 60.0,separatesHu,rate),
                    2)
                states.value = state
            }
        }
        return StateBinder()
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
    }
}